/**
 * \file ThreadManager_Linux.cpp
 * \brief ThreadManager declaration class
 * \author Edouard ROGE
 * \date 29 august 2012
 */

#include <algorithm>
#include <pthread.h>
#include "Thread.h"
#include "ThreadManager.h"

ThreadManager::ThreadManager()
{
	m_Threads.reserve(MAX_THREAD);
}

ThreadManager::~ThreadManager()
{

}

uint32 ThreadManager::GetMaxThread() const
{
	return MAX_THREAD;
}

uint32 ThreadManager::GetRunningThreads() const
{
	return m_Threads.size();
}

void ThreadManager::Register(Thread * _pThread)
{
	_pThread->m_parentThread = pthread_self();
	pthread_create(&_pThread->m_thread, NULL, Thread::RunTask, _pThread);
	m_Threads.push_back(_pThread);
}

void ThreadManager::Unregister(Thread * _pThread)
{
	std::vector<Thread*>::iterator it = std::find(std::begin(m_Threads), std::end(m_Threads), _pThread);
	if(it!=m_Threads.end())
	{
		pthread_cancel(_pThread->m_thread);
		m_Threads.erase(it);
	}
}

void ThreadManager::Clear()
{
	for(uint32 i=0; i<m_Threads.size(); ++i)
	{
		pthread_join(m_Threads[i]->m_thread, NULL);
		delete m_Threads[i];
	}
	m_Threads.clear();
}

